const express = require('express')
const app = express()
const path = require('path')
const tagRouter = require('./routes/tagRouter')
const userRouter = require('./routes/userRouter')
const articleRouter = require('./routes/articleRouter')
const UploadRouter = require('./routes/uploadRouter')
const ArtitalkRouter = require('./routes/artitalkRouter')

const session = require('express-session')

//跨域问题解决方面
const cors = require('cors');  
// 开放资源的访问权限
app.use('/public/', express.static(path.join(__dirname, './public/')))
app.use('/upload/',express.static(path.join(__dirname,'./upload/')))
app.use('/node_modules/', express.static(path.join(__dirname, './node_modules')))
// 配置接收post参数 body-parser
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({
  extended: false
}))
// parse application/json 
app.use(express.json())

app.use(session({
  // 配置加密字符串，它会在原有加密基础之上和这个字符串拼起来去加密
  // 目的是为了增加安全性，防止客户端恶意伪造
  secret: 'feng',
  resave: false,
  saveUninitialized: false
}))
//跨域问题解决方面
app.use(cors({  
    origin:['http://localhost:8080'],
    methods:['GET','POST'],
}));
//跨域问题解决方面
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  // 前端将token加到请求头上后跨域失败  在这里设置接受token和Authorization
  res.header('Access-Control-Allow-Headers', 'Content-Type,Token,Authorization');
  res.header('Access-Control-Allow-Credentials','true');
  next();
});



// 路由挂载
app.use(tagRouter)
app.use(userRouter)
app.use(articleRouter)
app.use(UploadRouter)
app.use(ArtitalkRouter)

app.use((req,res,next) => {
  const url = req._parsedUrl.pathname
  console.log(url);
})


app.listen(3000,() => {
  console.log('服务器启动成功，请访问http://127.0.0.1:3000')
})